package com.lqs.blog.service;

import com.lqs.blog.pojo.Admin;
import com.lqs.blog.pojo.Permission;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class AuthService {
    @Autowired
    private AdminService adminService;

    public boolean auth(HttpServletRequest request, Authentication authentication) {
        //权限认证
        //请求路径
        String requestURI = request.getRequestURI();
        Object principal = authentication.getPrincipal();
        if (principal == null || principal.equals("anonymousUser")) {//匿名用户
            //登录失败
            return false;
        }
        UserDetails userDetails = (UserDetails) principal;
        String username = userDetails.getUsername();
        Admin admin = adminService.findAdminByUsername(username);
        if (admin == null) {
            return false;
        }

        if (admin.getId() == 1) {
            //超级管理员
            return true;
        }
        Long id = admin.getId();
        requestURI = StringUtils.split(requestURI, '?')[0];
        List<Permission> permissions = this.adminService.findPermissionByAdminId(id);
        for (Permission permission : permissions) {
            if (permission.getPath().equals(requestURI)) {
                return true;
            }
        }

        return false;
    }
}
